import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_select_terminal_page.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/system_ui_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'building_index_diy_detail_page.dart';
import 'building_index_select_terminal_page.dart';
import 'building_index_terminal_list_response_bean.dart';

///楼层指示牌设置参数页面
class BuildingIndexSetTerminalPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "BuildingIndexSetTerminalPage";

  static const String INDEX_TOP_INFO_API =ServerApi.BASE_URL + "app/appTerminalManageHome";
  final String buildingIndexId;
  final String picurl;
  final List<HsnListBean> terminalList;
  final String hsns;
  const BuildingIndexSetTerminalPage({Key key, this.buildingIndexId,
    this.picurl, this.terminalList, this.hsns}):super(key: key);

  @override
  _BuildingIndexSetTerminalPageState createState() => _BuildingIndexSetTerminalPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, String buildingIndexId, String picurl,
      List<HsnListBean> terminalList, String hsns) {
    return RouterUtils.routeForFutureResult(
      context,
      BuildingIndexSetTerminalPage(
        buildingIndexId: buildingIndexId,
        picurl: picurl,
        terminalList: terminalList,
        hsns: hsns,
      ),
      routeName: BuildingIndexSetTerminalPage.ROUTER,
    );
  }
}

class _BuildingIndexSetTerminalPageState extends BaseState<BuildingIndexSetTerminalPage>{
  String _hsns = "";
  double _scale = 1.0;
  BuildingIndexViewModel _viewModel;
  int _allTerminalSize = 0;
  @override
  void initState() {
    super.initState();
    _viewModel = BuildingIndexViewModel(this);
    _allTerminalSize = widget?.terminalList?.length??0;
    _hsns = widget?.hsns;
    if(StringUtils.isEmpty(_hsns)){
      //如果无选中的终端，则默认选中所有终端
      widget?.terminalList?.forEach((element) {
        _hsns += element.hsn;
        _hsns += ",";
      });
      if(StringUtils.isNotEmpty(_hsns)){
        _hsns = _hsns.substring(0, _hsns.length-1);
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    _scale = ScreenUtils.screenW(context)/375;
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          body: Column(
            children: <Widget>[
              _toTopBarWidget(),
              _toBodyWidget(),
            ],
          ),
        )
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return WillPopScope(
      child: VgTopBarWidget(
        isShowBack: true,
        title:"播放文件·1",
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      ),
    );
  }

  Widget _toBodyWidget(){
    return Column(
      children: <Widget>[
        _showImageListWidget(),
        _playTerminalWidget(),
        SizedBox(height: 30,),
        _toConfirmWidget(),
      ],
    );
  }

  ///横向图片展示栏
  Widget _showImageListWidget(){
    double imageHeight = 251 *_scale;
    return Container(
      padding: EdgeInsets.only(top: 20, bottom: 17),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap:(){
            VgPhotoPreview.single(context, widget?.picurl);
          },
          child: _toSingleImageWidget(imageHeight)
      ),
    );
  }

  Widget _toSingleImageWidget(double imageHeight){
    VgCacheNetWorkImage image;
    image = VgCacheNetWorkImage(
        widget?.picurl ?? "",
        imageQualityType: ImageQualityType.high,
        fit: BoxFit.cover,
        placeWidget: Container(color: Colors.black,)
    );
    return Container(
      height: imageHeight,
      alignment: Alignment.center,
      child: image,
    );
  }


  ///播放终端
  Widget _playTerminalWidget(){
    String terminalHint = "";
    int selectedSize = StringUtils.isEmpty(_hsns)?0:_hsns.split(",").length;
    if(_allTerminalSize != 0){
      if(selectedSize == _allTerminalSize){
        terminalHint = "全部$selectedSize台终端";
      }else if(selectedSize == 0){
        terminalHint = "暂不选择终端";
      }else{
        terminalHint = "$selectedSize台终端";
      }
    }
    return Column(
      children: [
        GestureDetector(
          onTap: () async{
            String hsns = await BuildingIndexSelectTerminalPage.navigatorPush(context,
            widget?.buildingIndexId, _hsns, widget?.terminalList);
            if(hsns != null){
              setState(() {_hsns = hsns;});
            }
          },
          child: Container(
            height: 50,
            padding: EdgeInsets.symmetric(horizontal: 15),
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Row(
              children: <Widget>[
                Text(
                  "播放终端",
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                  ),
                ),
                Spacer(),
                Row(
                  children: <Widget>[
                    Text(
                      terminalHint,
                      style: TextStyle(
                        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                        fontSize: 14,
                        height: 1.2,
                      ),
                    ),
                    SizedBox(width: 9,),
                    Image.asset(
                      "images/index_arrow_ico.png",
                      width: 6,
                    )
                  ],
                ),
              ],
            ),
          ),
        ),
        Visibility(
            visible: selectedSize != 0,
            child: _toSplitLineWidget()
        ),
      ],
    );
  }


  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 15, right: 0),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///确定
  Widget _toConfirmWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      unSelectBgColor: Color(0xFF3A3F50),
      selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
        color: VgColors.INPUT_BG_COLOR,
        fontSize: 15,
      ),
      selectedTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15,
        // fontWeight: FontWeight.w600
      ),
      text: "确定",
      onTap: (){
        _doConfirm();
      },
    );
  }

  _doConfirm(){
    _viewModel.pushBuildingIndex(context, widget?.buildingIndexId, _hsns, (){
      RouterUtils.popUntil(context, BuildingIndexDiyDetailPage.ROUTER);
    });
  }

}